/*移动端返回事件处理*/
function judgeOnBack() {
    return 1; //1回到工作台
}
$(function () {
    if(sessionStorage.partType==4){
        $('.scrap').hide();$('.lose').hide();
        $('.qualityLi').hide();
    }else {
        //基础信息
        var qualityHtml='<p><span>已质检数量：</span>'+localStorage.qualityCountTotalSun +'</p>' +
            '<p><span>不合格数量：</span>'+localStorage.unqualityCountTotalSun+'</p>' +
            '<p><span>质检批次号：</span>'+localStorage.batch+'</p>';

        $('.qualityInfo').html(qualityHtml);
    }
    //质检完成 交班（金属）
    function metail(Obj) {
        this.obj={
            qualityId:"",
            qualityCount:0,
            unqualityCount:0,
            batch:'',
            result:0,
            type:0,
            img1:'',
            img2:'',
            img3:'',
            img4:'',
            scrap:'',
            lose:'',
            rework:'',
        };

        var parameterObj=$.extend(this.obj,Obj);
        var url='/mes/zw/quality/handle/metail';
        var mdObj=md5Fun(appUserId,url,appToken);
        var parameter=Encrypt(JSON.stringify(parameterObj));
        console.log(parameter)
        console.log(Decrypt(parameter));
        $.ajax({
            type: "POST",
            timeout : 5000,
            url: webUrlCon+url,
            data:JSON.stringify(
                {"parameter":parameter}
            ),
            beforeSend: function(request) {
                request.setRequestHeader("Content-Type", "application/json");
                request.setRequestHeader("sequence", mdObj.sequence);
                request.setRequestHeader("nonceStr", mdObj.nonceStr);
                request.setRequestHeader("userId", appUserId);
                request.setRequestHeader("token",appToken);
                //xmlhttp.setRequestHeader("infName", url);
                //xmlhttp.setRequestHeader("osVersion", '');
                request.setRequestHeader("versionType", "1");
                request.setRequestHeader("osPlatform", mdObj.osPlatform);
                request.setRequestHeader("appVersion", mdObj.appVersion);
                request.setRequestHeader("sign", mdObj.sign);
            },
            success: function (data) {
                console.log(data);
                if(data.code==100){
                    layer.open({
                        content: '提交成功'
                        ,btn: '确定'
                        ,shadeClose:false
                        , yes: function(index){
                            layer.close(index)
                            //location.reload()
                            //location.href='testHistory.html';
                            if (u.indexOf('iPhone') > -1) {   //苹果手机
                                location.href='qualityHistory.html';
                            }else {
                                jsObj.openHyperLinkReference('qualityHistory.html');
                            }
                        }
                    });
                }else{
                    layer.open({
                        content: data.code+' '+data.message
                        ,btn: '确定'
                    });
                }
            },
            error: function(e) {
                layer.open({
                    content: '无法请求服务器，请稍后再试！'
                    ,btn: '确定'
                });
            }
        });
    }
    
    //加减
    $('body').on('click', '.numberInp .add', function () {
        var num=$(this).siblings('span').find('input').val()==''?0:$(this).siblings('span').find('input').val();
        $(this).siblings('span').find('input').val(parseInt(num)+1);
        $(this).siblings('.del').removeClass('no');
    });
    $('body').on('click', '.numberInp .del', function () {
        if(!$(this).hasClass('no')){
            var num=$(this).siblings('span').find('input').val()==''?0:$(this).siblings('span').find('input').val();
            $(this).siblings('span').find('input').val(parseInt(num)-1);
            if($(this).siblings('span').find('input').val()<=0){
                $(this).addClass('no');
                $(this).siblings('span').find('input').val('');
                if($(this).parents('.content').hasClass('personDel')){
                    $(this).parents('.content').remove();
                }
            }
        }
    });
    $('body').on('blur', '.numberInp .number', function () {
        if($(this).val()!=''){
            if($(this).val()==0||$(this).val()=='0'){
                $(this).val('');
                $(this).parent('span').siblings('.del').addClass('no');
            }else {
                $(this).parent('span').siblings('.del').removeClass('no');
            }
        }else{
            $(this).parent('span').siblings('.del').addClass('no');
        }
    });


    //选择返工工序
    var tagRework='';
    $('body').on('click', '.reworkProcedure', function () {
        tagRework=this;
        $('#reworkProcedure').trigger('click');
    });
    //选择负责人
    $('body').on('click', '.personName', function () {
        //alert('personName')
        tagPerson=this;
        $('#personName').trigger('click');
    });
    //增加处理负责人
    $('body').on('click', '.handleAdd', function () {
        if($(this).hasClass('isRework')){  //返工工序
            $(this).parents('li').append('<div class="content personDel"> <div class="personBox"><span class="txt">负责人</span><span class="personName"></span><i class="iconfont icon-youjiantou"></i></div><div class="personBox" style=" height: 1rem; line-height: 1rem;"><span class="txt">返工工序</span><span class="reworkProcedure"></span><i class="iconfont icon-youjiantou"></i></div> <div class="numberBox">数量<div class="numberInp"><i class="del iconfont icon-jianshao"></i><span><input class="number" type="number" onkeyup="this.value=this.value.replace(/\\D/g,\'\')" onafterpaste="this.value=this.value.replace(/\\D/g,\'\')" placeholder="0" value="1"></span><i class="add iconfont icon-zengjia"></i></div></div> </div>');
        }else{
            $(this).parents('li').append('<div class="content personDel"> <div class="personBox"><span class="txt">负责人</span><span class="personName"></span><i class="iconfont icon-youjiantou"></i></div> <div class="numberBox">数量<div class="numberInp"><i class="del iconfont icon-jianshao"></i><span><input class="number" type="number" onkeyup="this.value=this.value.replace(/\\D/g,\'\')" onafterpaste="this.value=this.value.replace(/\\D/g,\'\')" placeholder="0" value="1"></span><i class="add iconfont icon-zengjia"></i></div></div> </div>');
        }
    });
    //提交
    $('body').on('click', '.UnqualBut', function () {
        var isshiftObj='0'; //1负责人  2返工工序
        if(sessionStorage.partType==4){
            var shiftObj={
                qualityId:localStorage.qualityId,
                qualityCount:localStorage.qualityCount,
                result:localStorage.result,
                type:localStorage.qualType,
                img1:localStorage.img1,
                img2:localStorage.img2,
                img3:localStorage.img3,
                img4:localStorage.img4,
                scrap:'',
                lose:'',
                rework:'',
            }
        }else {
            var shiftObj={
                qualityId:localStorage.qualityId,
                qualityCount:localStorage.qualityCount,
                unqualityCount:localStorage.unqualityCount||0,
                batch:localStorage.batch||'',
                result:localStorage.result,
                type:localStorage.qualType,
                img1:localStorage.img1,
                img2:localStorage.img2,
                img3:localStorage.img3,
                img4:localStorage.img4,
                scrap:'',
                lose:'',
                rework:'',
            }
        }

        var ObjCon={
            user:'',
            count:'',
        }
        var contSum=0;
        var scrap=[];
        $('.scrap .content').each(function () {
            if($(this).find('.personName').attr('user')!=undefined){
                ObjCon.user=$(this).find('.personName').attr('user');
                ObjCon.count=$(this).find('.number').val();
                contSum+=parseInt(ObjCon.count);
                scrap.push(ObjCon);
            }else{
                isshiftObj='1'
            }
        })
        var lose=[];
        $('.lose .content').each(function () {
            if($(this).find('.personName').attr('user')!=undefined) {
                ObjCon.user = $(this).find('.personName').attr('user');
                ObjCon.count = $(this).find('.number').val();
                contSum+=parseInt(ObjCon.count);
                lose.push(ObjCon);
            }else{
                isshiftObj='1'
            }
        })
        var rework=[];
        $('.rework .content').each(function () {
            if($(this).find('.personName').attr('user')!=undefined&&$(this).find('.reworkProcedure').attr('id')!=undefined) {
                ObjCon.user = $(this).find('.personName').attr('user');
                ObjCon.count = $(this).find('.number').val();
                ObjCon.id = $(this).find('.reworkProcedure').attr('id');
                contSum+=parseInt(ObjCon.count);
                rework.push(ObjCon);
            }else{
                if($(this).find('.personName').attr('user')==undefined){
                    isshiftObj='1'
                }else{
                    isshiftObj='2'
                }
            }
        })
        if(scrap.length==0){
            scrap='';
        }else{
            scrap=JSON.stringify(scrap);
        }
        if(lose.length==0){
            lose='';
        }else{
            lose=JSON.stringify(lose);
        }
        if(rework.length==0){
            rework='';
        }else{
            rework=JSON.stringify(rework);
        }

        shiftObj.scrap=scrap;
        shiftObj.lose=lose;
        shiftObj.rework=rework;
        if(isshiftObj=='0'){
            if(sessionStorage.partType==4){
                if(parseInt(localStorage.qualityCount)>=contSum){
                    metail(shiftObj)
                }else{
                    layer.open({
                        content: '返工数量不可大于质检数量，不能提交'
                        ,btn: '确定'
                    });
                }
            }else {
                if(contSum==parseInt(localStorage.unqualityCountTotalSun)){
                    metail(shiftObj)
                }else{
                    layer.open({
                        content: '零件处理数量不等于不合格数量，不能提交'
                        ,btn: '确定'
                    });
                }
            }

        }else if(isshiftObj=='1'){
            layer.open({
                content: '请选择负责人'
                ,btn: '确定'
            });
        }else if(isshiftObj=='2'){
            layer.open({
                content: '请选择返工工序'
                ,btn: '确定'
            });
        }
    });


    /*返工工序*/
    new MobileSelect({
        trigger: '#reworkProcedure',
        title: '返工工序',
        keyMap:{id:'id', value:'name'},
        wheels: [
            {data:JSON.parse(sessionStorage.reworkProcedure)},
        ],
        position:[0],
        callback:function(indexArr, data){
            $(tagRework).attr('id',data[0].id);
            $(tagRework).html(data[0].name);
        },
        transitionEnd:function(indexArr, data){

        }
    });

    var tagPerson='';
    //负责人
    var addressLocation='';
    var deptArr='';  //存放所有部门列表
    /*部门列表*/
    var isDept='';  //部门是否改变
    function dept() {
        var url='/test/mode/list/dept';
        var mdObj=md5Fun(appUserId,url,appToken);
        $.ajax({
            type: "POST",
            timeout : 5000,
            url: webUrlCon+url,
            beforeSend: function(request) {
                request.setRequestHeader("Content-Type", "application/json");
                request.setRequestHeader("sequence", mdObj.sequence);
                request.setRequestHeader("nonceStr", mdObj.nonceStr);
                request.setRequestHeader("userId", appUserId);
                request.setRequestHeader("token",appToken);
                //xmlhttp.setRequestHeader("infName", url);
                //xmlhttp.setRequestHeader("osVersion", '');
                request.setRequestHeader("versionType", "1");
                request.setRequestHeader("osPlatform", mdObj.osPlatform);
                request.setRequestHeader("appVersion", mdObj.appVersion);
                request.setRequestHeader("sign", mdObj.sign);
            },
            success: function (data) {
                //console.log('/test/mode/list/dept');
                //console.log(data);
                if(data.code==100) {
                    deptArr=Decrypt(data.content);
                    deptArr=JSON.parse(deptArr);
                    //console.log(deptArr);
                    /* 部门组别 */
                    var groupArr=[{'id':0,'value':'无'}];
                    var url='/test/mode/list/group';
                    var mdObj=md5Fun(appUserId,url,appToken);
                    var parameterObj= {
                        "deptId":deptArr[0].id
                    };
                    var parameter=Encrypt(JSON.stringify(parameterObj));
                    //console.log(parameter)
                    //console.log(Decrypt(parameter));
                    $.ajax({
                        type: "POST",
                        timeout : 5000,
                        url: webUrlCon+url,
                        data:JSON.stringify(
                            {"parameter":parameter}
                        ),
                        beforeSend: function(request) {
                            request.setRequestHeader("Content-Type", "application/json");
                            request.setRequestHeader("sequence", mdObj.sequence);
                            request.setRequestHeader("nonceStr", mdObj.nonceStr);
                            request.setRequestHeader("userId", appUserId);
                            request.setRequestHeader("token",appToken);
                            //xmlhttp.setRequestHeader("infName", url);
                            //xmlhttp.setRequestHeader("osVersion", '');
                            request.setRequestHeader("versionType", "1");
                            request.setRequestHeader("osPlatform", mdObj.osPlatform);
                            request.setRequestHeader("appVersion", mdObj.appVersion);
                            request.setRequestHeader("sign", mdObj.sign);
                        },
                        success: function (data) {
                            //console.log('/test/mode/list/group');
                            //console.log(data);
                            if(data.code==100) {
                                var groupArrObj=Decrypt(data.content);
                                groupArrObj=JSON.parse(groupArrObj);
                                //console.log(groupArrObj);
                                if(groupArrObj.length>0){
                                    groupArr=groupArrObj
                                }
                                /* 部门组别人员 */
                                var personnelArr=[{'id':0,'value':'无'}];
                                var url='/test/mode/list/user';
                                var mdObj=md5Fun(appUserId,url,appToken);
                                var parameterObj= {
                                    "groupId":groupArr[0].id
                                };
                                var parameter=Encrypt(JSON.stringify(parameterObj));
                                //console.log(parameter)
                                //console.log(Decrypt(parameter));
                                $.ajax({
                                    type: "POST",
                                    timeout : 5000,
                                    url: webUrlCon+url,
                                    data:JSON.stringify(
                                        {"parameter":parameter}
                                    ),
                                    beforeSend: function(request) {
                                        request.setRequestHeader("Content-Type", "application/json");
                                        request.setRequestHeader("sequence", mdObj.sequence);
                                        request.setRequestHeader("nonceStr", mdObj.nonceStr);
                                        request.setRequestHeader("userId", appUserId);
                                        request.setRequestHeader("token",appToken);
                                        //xmlhttp.setRequestHeader("infName", url);
                                        //xmlhttp.setRequestHeader("osVersion", '');
                                        request.setRequestHeader("versionType", "1");
                                        request.setRequestHeader("osPlatform", mdObj.osPlatform);
                                        request.setRequestHeader("appVersion", mdObj.appVersion);
                                        request.setRequestHeader("sign", mdObj.sign);
                                    },
                                    success: function (data) {
                                        //console.log('/test/mode/list/group');
                                        //console.log(data);
                                        if(data.code==100) {
                                            var personnelArrObj=Decrypt(data.content);
                                            personnelArrObj=JSON.parse(personnelArrObj);
                                            //console.log(groupArrObj);
                                            if(personnelArrObj.length>0){
                                                personnelArr=personnelArrObj
                                            }
                                            addressLocation= new MobileSelect({
                                                trigger: '#personName',
                                                title: '负责人',
                                                wheels: [
                                                    {data:deptArr},
                                                    {data:groupArr},
                                                    {data:personnelArr}
                                                ],
                                                position:[0,0,0],
                                                callback:function(indexArr, data){
                                                    if(data[2].id!=0){
                                                        $(tagPerson).attr('user',data[2].id);
                                                    }
                                                    $(tagPerson).html(data[2].value);
                                                },
                                                transitionEnd:function(indexArr, data){
                                                    console.log('isDeptId='+isDeptId+' isGroup='+isGroup);
                                                    console.log(data)
                                                    //console.log('data[0].id='+data[0].id+' data[1].id='+data[1].id)
                                                    //group(data[0].id);
                                                    if(isDeptId!=data[0].id){
                                                        group(data[0].id);
                                                    }else if(isGroup!=data[1].id){
                                                        personnel(data[1].id);
                                                    }
                                                    //console.log(indexArr); //
                                                    //console.log(data); //返回选中的json数据
                                                   // group(data[0].id);
                                                }
                                            });
                                            console.log(addressLocation.getValue())
                                            isDeptId=addressLocation.getValue()[0].id;
                                            isGroup=addressLocation.getValue()[0].id;
                                        }
                                    }
                                });
                            }
                        }
                    });
                }
            },
            error: function(e) {

            }
        });
    }
    dept();
    /*部门组别列表*/
    var isDeptId='';  //是否请求部门组别数据
    function group(deptId) {
        var url='/test/mode/list/group';
        var mdObj=md5Fun(appUserId,url,appToken);
        var parameterObj= {
            "deptId":deptId
        };
        var parameter=Encrypt(JSON.stringify(parameterObj));
        if(isDeptId!=deptId){
            $.ajax({
                type: "POST",
                timeout : 5000,
                url: webUrlCon+url,
                data:JSON.stringify(
                    {"parameter":parameter}
                ),
                beforeSend: function(request) {
                    request.setRequestHeader("Content-Type", "application/json");
                    request.setRequestHeader("sequence", mdObj.sequence);
                    request.setRequestHeader("nonceStr", mdObj.nonceStr);
                    request.setRequestHeader("userId", appUserId);
                    request.setRequestHeader("token",appToken);
                    //xmlhttp.setRequestHeader("infName", url);
                    //xmlhttp.setRequestHeader("osVersion", '');
                    request.setRequestHeader("versionType", "1");
                    request.setRequestHeader("osPlatform", mdObj.osPlatform);
                    request.setRequestHeader("appVersion", mdObj.appVersion);
                    request.setRequestHeader("sign", mdObj.sign);
                },
                success: function (data) {
                    //console.log('/test/mode/list/groupArrgroupArrgroupArrgroupArr');
                    //console.log(data);
                    if(data.code==100) {
                        var groupArr=Decrypt(data.content);
                        groupArr=JSON.parse(groupArr);
                        //console.log(groupArr);
                        if(groupArr.length==0){
                            groupArr.push({'id':0,'value':'无'})
                        }
                        addressLocation.updateWheel(1,groupArr);
                        addressLocation.locatePostion(1,0);
                        personnel(groupArr[0].id);
                    }
                },
            });
        }
        isDeptId=deptId;
    }
    /*部门组人员列表*/
    var isGroup='';  //是否请求部门组别人员数据
    function personnel(groupId) {
        var url='/test/mode/list/user';
        var mdObj=md5Fun(appUserId,url,appToken);
        var parameterObj= {
            "groupId":groupId
        };
        var parameter=Encrypt(JSON.stringify(parameterObj));
        if(isGroup!=groupId){
            $.ajax({
                type: "POST",
                timeout : 5000,
                url: webUrlCon+url,
                data:JSON.stringify(
                    {"parameter":parameter}
                ),
                beforeSend: function(request) {
                    request.setRequestHeader("Content-Type", "application/json");
                    request.setRequestHeader("sequence", mdObj.sequence);
                    request.setRequestHeader("nonceStr", mdObj.nonceStr);
                    request.setRequestHeader("userId", appUserId);
                    request.setRequestHeader("token",appToken);
                    //xmlhttp.setRequestHeader("infName", url);
                    //xmlhttp.setRequestHeader("osVersion", '');
                    request.setRequestHeader("versionType", "1");
                    request.setRequestHeader("osPlatform", mdObj.osPlatform);
                    request.setRequestHeader("appVersion", mdObj.appVersion);
                    request.setRequestHeader("sign", mdObj.sign);
                },
                success: function (data) {
                    //console.log('/test/mode/list/groupArrgroupArrgroupArrgroupArr');
                    //console.log(data);
                    if(data.code==100) {
                        var personnelArr=Decrypt(data.content);
                        personnelArr=JSON.parse(personnelArr);
                        //console.log(groupArr);
                        if(personnelArr.length==0){
                            personnelArr.push({'id':0,'value':'无'})
                        }
                        addressLocation.updateWheel(2,personnelArr);
                        addressLocation.locatePostion(2,0);
                        isDeptId=addressLocation.getValue()[0].id;
                        isGroup=addressLocation.getValue()[1].id;
                    }
                },
            });
        }
        isGroup=groupId;
    }


})


